package com.niiwoo.civet.user.service.duboo.customsystem;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dto.common.UserAccountInfoDTO;
import com.niiwoo.civet.account.dto.request.QueryMoneyTotalRequestDTO;
import com.niiwoo.civet.account.dto.response.*;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.account.service.MoneyTotalDubboService;
import com.niiwoo.civet.account.service.WithdrawDubboService;
import com.niiwoo.civet.account.service.bankcard.BankCardDubboService;
import com.niiwoo.civet.account.service.recharge.RechargeDubboService;
import com.niiwoo.civet.base.enums.DeadlineUnitEnum;
import com.niiwoo.civet.trade.dto.common.ProjectBorrowerSummaryDTO;
import com.niiwoo.civet.trade.dto.common.ProjectDTO;
import com.niiwoo.civet.trade.dto.response.CurrentPeriodToReturnDTO;
import com.niiwoo.civet.trade.dto.response.CustomSysBorrowerInfoDTO;
import com.niiwoo.civet.trade.dto.response.customsystem.QueryProjectInvestOrderResponseDTO;
import com.niiwoo.civet.trade.enums.BorrowerPlanRefundStatusEnum;
import com.niiwoo.civet.trade.enums.ProjectStatusEnum;
import com.niiwoo.civet.trade.enums.RepayStatusEnum;
import com.niiwoo.civet.trade.service.invest.InvestOrderDetailDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.user.dao.entity.*;
import com.niiwoo.civet.user.dao.mapper.*;
import com.niiwoo.civet.user.dto.UserPersonalDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserProfessionDubboInfoDTO;
import com.niiwoo.civet.user.dto.request.customsystem.QueryBorrowerUserRequestDTO;
import com.niiwoo.civet.user.dto.request.customsystem.QueryLastProjectRequestDTO;
import com.niiwoo.civet.user.dto.request.customsystem.QueryUserListForSyncRequestDTO;
import com.niiwoo.civet.user.dto.request.customsystem.QueryUserListRequestDTO;
import com.niiwoo.civet.user.dto.response.UserExtInfoResponseDTO;
import com.niiwoo.civet.user.dto.response.customsystem.QueryBorrowerUserResponseDTO;
import com.niiwoo.civet.user.dto.response.customsystem.QueryLastProjectResponseDTO;
import com.niiwoo.civet.user.dto.response.customsystem.QueryUserListForSyncResponseDTO;
import com.niiwoo.civet.user.dto.response.customsystem.QueryUserListResponseDTO;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.civet.user.service.UserExtInfoDubboService;
import com.niiwoo.civet.user.service.customsystem.CustomSystemUserDubboService;
import com.niiwoo.civet.user.service.local.UserBasicInfoService;
import com.niiwoo.civet.user.service.local.UserCreditService;
import com.niiwoo.civet.user.service.local.UserDataService;
import com.niiwoo.civet.user.service.local.UserIdentityService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.base.utils.DateUtils;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service(version = "1.0.0")
public class CustomSystemUserDubboServiceImpl implements CustomSystemUserDubboService {
    @Autowired
    UserBasicInfoService userBasicInfoService;
    @Autowired
    PrivacyMasks privacyMasks;
    @Autowired
    UserExtInfoDubboService userExtInfoDubboService;
    @Autowired
    UserIdentityService userIdentityService;
    @Autowired
    UserDataService userDataService;
    @Autowired
    UserCreditService userCreditService;
    @Autowired
    UserCreditProcessMapperExt userCreditProcessMapperExt;
    @Autowired
    UserExtInfoMapperExt userExtInfoMapperExt;
    @Autowired
    UserAuthorizationInfoMapperExt userAuthorizationInfoMapperExt;
    @Autowired
    DataStatusMapperExt dataStatusMapperExt;
    @Reference(version = "1.0.0")
    RechargeDubboService rechargeDubboService;
    @Reference(version = "1.0.0")
    WithdrawDubboService withdrawDubboService;
    @Reference(version = "1.0.0")
    ProjectDubboService projectDubboService;
    @Autowired
    UserBlackListMapperExt userBlackListMapperExt;
    @Reference(version = "1.0.0")
    InvestOrderDetailDubboService investOrderDetailDubboService;
    @Reference(version = "1.0.0")
    AccountDubboService accountDubboService;
    @Reference(version = "1.0.0")
    BankCardDubboService bankCardDubboService;
    @Reference(version = "1.0.0")
    MoneyTotalDubboService moneyTotalDubboService;

    @Override
    public List<QueryUserListResponseDTO> queryUserList(QueryUserListRequestDTO queryUserListRequestDTO) {
        log.info("客服系统查询用户列表,请求参数={}",JSON.toJSONString(queryUserListRequestDTO));
        List<UserBasicInfo> userBasicInfoList = userBasicInfoService.queryCustomSystemUserList(queryUserListRequestDTO);
        List<QueryUserListResponseDTO> queryUserListResponseDTOList = new ArrayList<QueryUserListResponseDTO>();
        try {
            if (userBasicInfoList != null && userBasicInfoList.size() > 0) {
                for (UserBasicInfo userBasicInfo : userBasicInfoList) {
                    UserExtInfoResponseDTO userExtInfoResponseDTO = userExtInfoDubboService.queryUserBasicInfo(userBasicInfo.getUserId());
                    IdentityInfo identityInfo = userIdentityService.getByUserId(userBasicInfo.getUserId());
                    UserPersonalDubboInfoDTO userPersonalDubboInfoDTO = userDataService.userPersonalInfo(userBasicInfo.getUserId());
                    UserCreditInfo userCreditInfo = userCreditService.getUserCreditInfoByType(userBasicInfo.getUserId(), (byte) 1);

                    QueryUserListResponseDTO queryUserListResponseDTO = new QueryUserListResponseDTO();
                    //注册时间
                    queryUserListResponseDTO.setRegisterDate(userBasicInfo.getCreateTime() == null ? null : DateUtils.format(userBasicInfo.getCreateTime(), DateUtils.SHOW_DATETIME_FORMAT));
                    //注册渠道
                    queryUserListResponseDTO.setRegisterChannel(userBasicInfo.getRegisterChannel() == null ? null : userBasicInfo.getRegisterChannel());
                    //设备类型
                    queryUserListResponseDTO.setDeviceType(userExtInfoResponseDTO.getDeviceType() == null ? null : userExtInfoResponseDTO.getDeviceType());
                    //身份标记
                    Byte identityTag = 0;
                    if (StringUtils.isNotEmpty(userBasicInfo.getIdentityTag())) {
                        String[] identityTagArray = userBasicInfo.getIdentityTag().split(",");
                        List<String> identityTagList = Arrays.asList(identityTagArray);
                        if (identityTagList.size() == 1 && identityTagList.contains("1")) {
                            identityTag = 1;
                        } else if (identityTagList.size() == 1 && identityTagList.contains("2")) {
                            identityTag = 2;
                        } else if (identityTagList.size() == 1 && identityTagList.contains("3")) {
                            identityTag = 3;
                        } else if (identityTagList.size() == 2 && identityTagList.contains("2") && identityTagList.contains("3")) {
                            identityTag = 100;
                        }
                    }
                    queryUserListResponseDTO.setIdentityTag(identityTag);

                    //昵称
                    queryUserListResponseDTO.setNickName(userBasicInfo.getNickName());
                    //姓名
                    queryUserListResponseDTO.setRealName(identityInfo == null ? null : (StringUtils.isEmpty(identityInfo.getName()) ? null : identityInfo.getName()));
                    //性别
                    queryUserListResponseDTO.setSex(userBasicInfo.getGender() == null ? null : userBasicInfo.getGender());
                    //手机号码
                    queryUserListResponseDTO.setMobileNo(StringUtils.isEmpty(userBasicInfo.getMobileNo()) ? null : privacyMasks.decryptPrivacy(userBasicInfo.getMobileNo()));
                    List<AccountBaseResponse> accountBases = accountDubboService.listNiiwooAccountByUserId(userBasicInfo.getUserId());
                    //电子邮箱
                    queryUserListResponseDTO.setEmail(userPersonalDubboInfoDTO == null ? null : userPersonalDubboInfoDTO.getEmail());
                    //居住地址
                    queryUserListResponseDTO.setAddress(userPersonalDubboInfoDTO == null ? null : (StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingProvince()) ? "" : userPersonalDubboInfoDTO.getLivingProvince().concat(StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingCity()) ? "" : userPersonalDubboInfoDTO.getLivingCity()).concat(StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingArea()) ? "" : userPersonalDubboInfoDTO.getLivingArea()).concat(StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingAddress()) ? "" : userPersonalDubboInfoDTO.getLivingAddress())));
                    //极速借授信反欺诈结果
                    UserCreditProcess userCreditProcess = userCreditProcessMapperExt.selectByUserAndType(userBasicInfo.getUserId(), (byte) 1);
                    queryUserListResponseDTO.setSpeedLoanFraudLibra(userCreditProcess == null ? 0 : (userCreditProcess.getAntifraudStatus() == null ? 0 : userCreditProcess.getAntifraudStatus()));
                    //最后登录时间
                    UserExtInfo userExtInfo = userExtInfoMapperExt.selectByPrimaryKey(userBasicInfo.getUserId());
                    queryUserListResponseDTO.setLastLoginDate(userExtInfo == null ? null : (userExtInfo.getUpdateTime() == null ? null : DateUtils.format(userExtInfo.getUpdateTime(), DateUtils.SHOW_DATETIME_FORMAT)));
                    //芝麻分
                    UserAuthorizationInfo userAuthorizationInfo = userAuthorizationInfoMapperExt.selectByPrimaryKey(userBasicInfo.getUserId());
                    queryUserListResponseDTO.setSesameScore(userAuthorizationInfo.getZhimaScore());
                    //社保数据验证状态
                    DataStatus dataStatus = dataStatusMapperExt.selectByUserIdAndType(userBasicInfo.getUserId(), UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE.getValue());
                    queryUserListResponseDTO.setSocialSecurityVerifyState(dataStatus == null ? 0 : (dataStatus.getDataStatus() == null ? 0 : dataStatus.getDataStatus()));
                    //帐户余额
                    queryUserListResponseDTO.setAccountAmount(this.getBalanceAmountTotal(accountBases));
                    //待收本息
                    QueryMoneyTotalRequestDTO queryMoneyTotalRequestDTO = new QueryMoneyTotalRequestDTO();
                    queryMoneyTotalRequestDTO.setUserId(userBasicInfo.getUserId());
                    QueryMoneyTotalResponseDTO queryMoneyTotalResponseDTO = moneyTotalDubboService.queryMoneyTotal(queryMoneyTotalRequestDTO);
                    if(queryMoneyTotalResponseDTO != null) {
                        queryUserListResponseDTO.setDueInPrincipalAndInterest(queryMoneyTotalResponseDTO.getDueInCorpusInterest());
                    }else {
                        queryUserListResponseDTO.setDueInPrincipalAndInterest(BigDecimal.ZERO);
                    }
                    RechargeOrderDTO rechargeOrderDTO = rechargeDubboService.queryFirstRechrageSuccessRecord(userBasicInfo.getUserId());
                    BigDecimal totalRechrageAmount = rechargeDubboService.queryUserTotalRechrageAmount(userBasicInfo.getUserId());
                    //首次充值时间
                    queryUserListResponseDTO.setFirstRechargeTime(rechargeOrderDTO == null ? null : (rechargeOrderDTO.getCreateTime() == null ? null : DateUtils.format(rechargeOrderDTO.getCreateTime(), DateUtils.SHOW_DATETIME_FORMAT)));
                    //首次充值金额
                    queryUserListResponseDTO.setFirstRechargeAmount(rechargeOrderDTO == null ? null : rechargeOrderDTO.getAmount());
                    //累计充值金额
                    queryUserListResponseDTO.setTotalRechargeAmount(totalRechrageAmount);
                    WithdrawOrderResponseDTO withdrawOrderResponseDTO = withdrawDubboService.queryLastWithdrawSuccessRecord(userBasicInfo.getUserId());
                    //最近提现金额
                    queryUserListResponseDTO.setLastWithdrawAmount(withdrawOrderResponseDTO == null ? null : withdrawOrderResponseDTO.getAmount());
                    //最近提现时间
                    queryUserListResponseDTO.setLastWithdrawTime(withdrawOrderResponseDTO == null ? null : (withdrawOrderResponseDTO.getCreateTime() == null ? null : DateUtils.format(withdrawOrderResponseDTO.getCreateTime(), DateUtils.SHOW_DATETIME_FORMAT)));
                    Integer inAuditProjectCount = projectDubboService.queryInAuditProjectCount(userBasicInfo.getUserId());
                    //审核中借款笔数
                    queryUserListResponseDTO.setAuditingLoanTimes(inAuditProjectCount);
                    //出生日期
                    queryUserListResponseDTO.setBirthday(identityInfo == null ? null : (identityInfo.getBirthday() == null ? null : DateUtils.format(identityInfo.getBirthday(), DateUtils.SHOW_DATE_FORMAT)));
                    //极速借授信额度
                    queryUserListResponseDTO.setFastBorrowCreditAmount(userCreditInfo == null ? null : userCreditInfo.getCreditAmount());
                    //学历
                    queryUserListResponseDTO.setStudentLeve(userPersonalDubboInfoDTO == null ? null : userPersonalDubboInfoDTO.getEducationLevel());
                    UserBlackList userBlackList = userBlackListMapperExt.selectLastOneByUserId(userBasicInfo.getUserId());
                    //名单类型
                    queryUserListResponseDTO.setListType(userBlackList == null ? null : userBlackList.getListType());
                    Integer projectCount = projectDubboService.queryProjectCountByUserId(userBasicInfo.getUserId());
                    //极速借提交借款笔数
                    queryUserListResponseDTO.setSpeedBorrowCount(projectCount);
                    //下载渠道
                    queryUserListResponseDTO.setDownloadChannel(userExtInfo.getAppDownloadChannel());
                    //最近借款状态
                    ProjectDTO projectDTO = projectDubboService.queryLastProjectByUserId(userBasicInfo.getUserId());
                    queryUserListResponseDTO.setLastLoanStatus(projectDTO == null ? null : projectDTO.getStatus());
                    //最近借款类型
                    queryUserListResponseDTO.setLastLoanType(projectDTO == null ? null : projectDTO.getType());
                    //最近借款申请时间
                    queryUserListResponseDTO.setLastLoanApplyTime(projectDTO == null ? null : (projectDTO.getSubmitTime() == null ? null : DateUtils.format(projectDTO.getSubmitTime(), DateUtils.SHOW_DATETIME_FORMAT)));
                    //最近借款申请金额
                    queryUserListResponseDTO.setLastLoanApplyAmount(projectDTO == null ? null : projectDTO.getHandAmount());
                    //累计投资金额
                    queryUserListResponseDTO.setTotalInvestAmount(investOrderDetailDubboService.queryTotalInvestSuccessAmount(userBasicInfo.getUserId()));
                    QueryProjectInvestOrderResponseDTO queryProjectInvestOrderResponseDTO = investOrderDetailDubboService.queryLastInvestOrderByUserId(userBasicInfo.getUserId());
                    //最近投资时间
                    queryUserListResponseDTO.setLastInvestTime(queryProjectInvestOrderResponseDTO == null ? null : (queryProjectInvestOrderResponseDTO.getInvestTime() == null ? null : DateUtils.format(queryProjectInvestOrderResponseDTO.getInvestTime(), DateUtils.SHOW_DATETIME_FORMAT)));
                    //最近投资金额
                    queryUserListResponseDTO.setLastInvestAmount(queryProjectInvestOrderResponseDTO == null ? null : queryProjectInvestOrderResponseDTO.getInvestAmount());

                    queryUserListResponseDTOList.add(queryUserListResponseDTO);
                }
            }
        }catch(Exception e){
            log.error("客服系统查询用户列表,请求参数={},发生系统异常,原因={}",JSON.toJSONString(queryUserListRequestDTO),e);
        }

        return queryUserListResponseDTOList;
    }

    //获取账户总余额
    private BigDecimal getBalanceAmountTotal(List<AccountBaseResponse> accountBases){
        UserAccountInfoDTO userAccountInfoDTO = new UserAccountInfoDTO();
        if (accountBases != null && accountBases.size() > 0) {
            accountBases.forEach(p -> {
                if (UserRoleEnum.INVESTOR.getValue().equals(p.getAccountRole())) {
                    userAccountInfoDTO.setBalanceAmountInvestor(p.getAvailableAmount());
                } else if (UserRoleEnum.BORROWERS.getValue().equals(p.getAccountRole())) {
                    userAccountInfoDTO.setBalanceAmountBorrower(p.getAvailableAmount());
                } else if (UserRoleEnum.GUARANTEECORP.getValue().equals(p.getAccountRole())) {
                    userAccountInfoDTO.setBalanceAmountGuarantee(p.getAvailableAmount());
                }
            });
        }
        return userAccountInfoDTO.getBalanceAmountTotal();
    }

    @Override
    public List<QueryUserListForSyncResponseDTO> queryUserListForSync(QueryUserListForSyncRequestDTO queryUserListForSyncRequestDTO) {
        log.info("客服系统同步用户信息,请求参数={}",JSON.toJSONString(queryUserListForSyncRequestDTO));
        List<QueryUserListForSyncResponseDTO> result=new ArrayList<QueryUserListForSyncResponseDTO>();
        try {
            List<UserBasicInfo> userBasicInfoList = userBasicInfoService.queryCustomSystemUserListForSync(queryUserListForSyncRequestDTO);
            if (userBasicInfoList != null && userBasicInfoList.size() > 0) {
                for (UserBasicInfo userBasicInfo : userBasicInfoList) {
                    QueryUserListForSyncResponseDTO queryUserListForSyncResponseDTO = new QueryUserListForSyncResponseDTO();
                    queryUserListForSyncResponseDTO.setMobileNo(userBasicInfo.getMobileNo() == null ? null : privacyMasks.decryptPrivacy(userBasicInfo.getMobileNo()));
                    queryUserListForSyncResponseDTO.setNickName(userBasicInfo.getNickName());
                    IdentityInfo identityInfo = userIdentityService.getByUserId(userBasicInfo.getUserId());
                    queryUserListForSyncResponseDTO.setRealName(identityInfo == null ? null : (identityInfo.getName() == null ? null : identityInfo.getName()));
                    queryUserListForSyncResponseDTO.setRegisterChannel(userBasicInfo.getRegisterChannel() == null ? null : userBasicInfo.getRegisterChannel());
                    queryUserListForSyncResponseDTO.setRegisterTime(DateUtils.format(userBasicInfo.getCreateTime(), DateUtils.SHOW_DATETIME_FORMAT));
                    queryUserListForSyncResponseDTO.setUserId(userBasicInfo.getUserId());

                    result.add(queryUserListForSyncResponseDTO);
                }
            }
        }catch(Exception e){
            log.error("客服系统同步用户信息,请求参数={},发生系统异常,原因={}",JSON.toJSONString(queryUserListForSyncRequestDTO),e);
        }

        return result;
    }

    @Override
    public QueryLastProjectResponseDTO queryUserLastProject(QueryLastProjectRequestDTO queryLastProjectRequestDTO) {
        log.info("客服系统查询最近一笔借款信息,请求参数={}",JSON.toJSONString(queryLastProjectRequestDTO));
        QueryLastProjectResponseDTO queryLastProjectResponseDTO=new QueryLastProjectResponseDTO();
        try {
            String userId = userBasicInfoService.queryUserIdByMobileNo(queryLastProjectRequestDTO.getMobileNo());
            if (StringUtils.isNotEmpty(userId)) {
                queryLastProjectResponseDTO = new QueryLastProjectResponseDTO();
                ProjectDTO projectDTO = projectDubboService.queryLastProjectByUserId(userId);
                IdentityInfo identityInfo = userIdentityService.getByUserId(userId);
                //姓名
                queryLastProjectResponseDTO.setRealName(identityInfo.getName());
                //手机号码
                queryLastProjectResponseDTO.setMobileNo(privacyMasks.decryptPrivacy(queryLastProjectRequestDTO.getMobileNo()));
                //身份证号码
                queryLastProjectResponseDTO.setIdcardNo(identityInfo == null || identityInfo.getIdCard() == null ? null : privacyMasks.decryptPrivacy(identityInfo.getIdCard()));
                if (projectDTO != null) {
                    //最近一笔借款利息
                    queryLastProjectResponseDTO.setWaitRepayInterest(projectDubboService.queryTotalInterestByProjectId(projectDTO.getProjectId()));
                    Integer loaningProjectCount = projectDubboService.queryLoaningProjectCount(userId);
                    //同时借款笔数(进行中的)
                    queryLastProjectResponseDTO.setLoaningProjectCount(loaningProjectCount);
                    //借款时间
                    queryLastProjectResponseDTO.setLoanTime(projectDTO.getSubmitTime() == null ? null : (DateUtils.format(projectDTO.getSubmitTime(), DateUtils.SHOW_DATETIME_FORMAT)));
                    //合同金额
                    queryLastProjectResponseDTO.setLoanAmount(projectDTO.getContractAmount());
                    //借款期限
                    queryLastProjectResponseDTO.setDeadline(projectDTO.getDeadline() == null ? null : (String.valueOf(projectDTO.getDeadline()).concat(projectDTO.getDeadlineUnit().equals(DeadlineUnitEnum.BY_MONTH.getDeadlineUnit()) ? "月" : "天")));
                    //逾期还款摘要信息
                    ProjectBorrowerSummaryDTO projectBorrowerSummaryDTO = projectDubboService.queryDueProjectBorrowerSummaryByProjectId(projectDTO.getProjectId());
                    if (projectBorrowerSummaryDTO != null) {
                        //逾期期数
                        queryLastProjectResponseDTO.setDuePeriod(projectBorrowerSummaryDTO.getCurrentPeriod());
                        //应还款时间
                        //queryLastProjectResponseDTO.setRepayTime(projectBorrowerSummaryDTO.getRefundDate() == null ? null : (DateUtils.format(projectBorrowerSummaryDTO.getRefundDate(), DateUtils.SHOW_DATETIME_FORMAT)));
                        //是否已还当期款,0:否;1:是;
                        queryLastProjectResponseDTO.setIsCurentPeriodRepayed(projectBorrowerSummaryDTO.getRepayStatus() == null ? null : (projectBorrowerSummaryDTO.getRepayStatus().equals(RepayStatusEnum.SETTLEMENT.getCode()) ? 1 : 0));
                        //逾期天数
                        queryLastProjectResponseDTO.setDueDays(isDue(projectBorrowerSummaryDTO.getRepayStatus()) ? (projectBorrowerSummaryDTO.getRefundDate() == null ? null : Long.valueOf(DateUtils.daysBetween(projectBorrowerSummaryDTO.getRefundDate(), new Date())).intValue()) : 0);
                    }
                    //当前标的是否结清,0:否;1:是;
                    queryLastProjectResponseDTO.setIsClose(projectDTO.getStatus() == null ? null : (projectDTO.getStatus().equals(ProjectStatusEnum.FINISH.getStatus()) ? 1 : 0));
                    //查询用户成功借款次数
                    queryLastProjectResponseDTO.setSuccessLoanCount(projectDubboService.queryLoanSuccessCount(userId));
                    //是否所有借款已结清
                    queryLastProjectResponseDTO.setIsAllLoanClose(loaningProjectCount == null || loaningProjectCount == 0 ? 1 : 0);

                    if(projectDTO.getStatus().equals(ProjectStatusEnum.REPAYING.getStatus())) {
                        CurrentPeriodToReturnDTO projectToReturnDTO = projectDubboService.queryCurrentPeriodToReturnByProjectId(projectDTO.getProjectId());
                        if (projectToReturnDTO != null) {
                            //当期剩余本金
                            queryLastProjectResponseDTO.setCurrentRepayPrincipal(projectToReturnDTO.getCurrentPeriodToReturnCapital());
                            //当期剩余罚息
                            queryLastProjectResponseDTO.setCurrentDueInterest(projectToReturnDTO.getCurrentPeriodToReturnPenaltyFee());
                            //当期剩余利息
                            queryLastProjectResponseDTO.setCurrentRepayInterest(projectToReturnDTO.getCurrentPeriodToReturnInterest());
                            //当期剩余管理费
                            queryLastProjectResponseDTO.setCurrentManageFee(projectToReturnDTO.getCurrentPeriodToReturnManagementFee());
                            //当期剩余担保服务费
                            queryLastProjectResponseDTO.setCurrentGuaranteeFee(projectToReturnDTO.getCurrentPeriodToReturnGuaranteeFee());
                        }
                    }
                    //标的ID
                    queryLastProjectResponseDTO.setProjectId(projectDTO.getProjectId());
                    //标的管理费
                    queryLastProjectResponseDTO.setManageFee(projectDTO.getManageFee());
                }

                UserProfessionDubboInfoDTO userProfessionDubboInfoDTO = userDataService.userProfessionInfo(userId);
                if (userProfessionDubboInfoDTO != null) {
                    //公司地址
                    queryLastProjectResponseDTO.setCompanyAddress(userProfessionDubboInfoDTO.getCompanyAddress());
                    //公司名称
                    queryLastProjectResponseDTO.setCompanyName(userProfessionDubboInfoDTO.getCompanyName());
                    //公司电话号码
                    queryLastProjectResponseDTO.setCompanyPhone(userProfessionDubboInfoDTO.getCompanyPhone());
                }

                //身份证地址
                queryLastProjectResponseDTO.setIdcardAddress(identityInfo == null ? null : identityInfo.getAddress());
                UserPersonalDubboInfoDTO userPersonalDubboInfoDTO = userDataService.userPersonalInfo(userId);
                if (userPersonalDubboInfoDTO != null) {
                    //居住地址
                    queryLastProjectResponseDTO.setLivingAddress(userPersonalDubboInfoDTO == null ? "" : (StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingProvince()) ? "" : userPersonalDubboInfoDTO.getLivingProvince())
                            .concat((StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingCity()) ? "" : userPersonalDubboInfoDTO.getLivingCity()))
                            .concat((StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingArea()) ? "" : userPersonalDubboInfoDTO.getLivingArea()))
                            .concat((StringUtils.isEmpty(userPersonalDubboInfoDTO.getLivingAddress()) ? "" : userPersonalDubboInfoDTO.getLivingAddress())));
                    //紧急联系人列表
                    queryLastProjectResponseDTO.setLinkManList(userPersonalDubboInfoDTO.getLinkManInfoList());
                }
                GetSimpleUserBankCardResponse getSimpleUserBankCardResponse = bankCardDubboService.getSimpleUserBankCard(userId);
                if (getSimpleUserBankCardResponse != null) {
                    //银行卡号
                    queryLastProjectResponseDTO.setBankCardNo(getSimpleUserBankCardResponse.getBankCard().getBankAccountNo());
                    //银行名称
                    queryLastProjectResponseDTO.setBankName(getSimpleUserBankCardResponse.getBankCard().getBankType().getBankName());
                    //是否支持代扣
                    queryLastProjectResponseDTO.setIsSupportWithhold(getSimpleUserBankCardResponse.isSupportWithhold() ? (byte) 1 : (byte) 0);
                }
              
                //最大逾期天数
                queryLastProjectResponseDTO.setMaxDueDays(projectDubboService.queryMaxDueDays(userId));
                //标的渠道来源
                List<String> fromSourceResult = projectDubboService.queryFromSourceListByUserId(userId);
                queryLastProjectResponseDTO.setFromSource(fromSourceResult);
                //获取当期还款数据信息
                CustomSysBorrowerInfoDTO currentPeriodRefundInfoDTO = projectDubboService.queryCurrentPeriodRefundInfoByProjectId(projectDTO.getProjectId());
                if(currentPeriodRefundInfoDTO != null) {
                	//本期
                    queryLastProjectResponseDTO.setCurrentPeriod(currentPeriodRefundInfoDTO.getCurrentPeriod());
                    //还款期数
                   queryLastProjectResponseDTO.setTotalPeriod(currentPeriodRefundInfoDTO.getTotalPeriod());
                   //本期还款时间
                   queryLastProjectResponseDTO.setRepayTime(currentPeriodRefundInfoDTO.getRefundDate() == null ? null : DateUtils.format(currentPeriodRefundInfoDTO.getRefundDate(), DateUtils.SHOW_DATETIME_FORMAT));
                   //本期待还 = capital + interest + penaltyFee + guaranteeFee + managementFee
                   queryLastProjectResponseDTO.setCurrentExpectedAmount(currentPeriodRefundInfoDTO.getCapital()
                		   																									.add(currentPeriodRefundInfoDTO.getInterest())
                		   																									.add(currentPeriodRefundInfoDTO.getGuaranteeFee())
                		   																									.add(currentPeriodRefundInfoDTO.getManagementFee())
                		   																									.add(currentPeriodRefundInfoDTO.getPenaltyFee()));
                }
                //待还总额
                List<CustomSysBorrowerInfoDTO> refundInfoList = projectDubboService.queryRefundListInfoByProjectId(projectDTO.getProjectId());
                if(refundInfoList != null && !refundInfoList.isEmpty()) {
                	BigDecimal totalExpectedAmount = BigDecimal.ZERO;
                	for (CustomSysBorrowerInfoDTO refundInfo : refundInfoList) {
						if(BorrowerPlanRefundStatusEnum.NON_REPAYMENT.equals(BorrowerPlanRefundStatusEnum.enumOf(refundInfo.getStatus()))) {
							totalExpectedAmount = totalExpectedAmount.add(refundInfo.getCapital())
																										    .add(refundInfo.getInterest())
																										    .add(refundInfo.getGuaranteeFee())
																										    .add(refundInfo.getManagementFee())
																										    .add(refundInfo.getPenaltyFee());
						}
					}
                	queryLastProjectResponseDTO.setTotalExpectedAmount(totalExpectedAmount);
                }
                
            }
        }catch(Exception e ){
            log.error("客服系统查询最近一笔借款信息,请求参数={},发生系统异常,原因={}",JSON.toJSONString(queryLastProjectRequestDTO),e);
        }

        return queryLastProjectResponseDTO;

    }

    /**
     * 是否逾期?
     * @param repayStatus
     * @return
     */
    private boolean isDue(Byte repayStatus){
        return repayStatus.equals((byte)2) || repayStatus.equals((byte)3);
    }
    
    @Override
    public List<QueryBorrowerUserResponseDTO> queryBorrowerUserListByLinkManPhoneNum(QueryBorrowerUserRequestDTO reqDTO) {
    	return userDataService.queryBorrowerUserListByLinkManPhoneNum(reqDTO);
    }

}
